<template>
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="'default'"
        status-icon
    >
        <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm">
                保存
            </el-button>
            <el-button type="primary" @click="submitAndNewForm">
                保存并新增</el-button
            >
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup name="Role">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { RoleModel } from '@/common/types/model';
import { Request } from '@/app/request';
import { isNil, keys, omit, omitBy, unset } from 'lodash';
import { ValidateFieldsError } from 'async-validator';

const props = defineProps<{
    role?: RoleModel;
}>();
const emit = defineEmits(['yh-newrole', 'yh-closedialog', 'yh-updaterole']);
const formRef = ref<FormInstance>();
const formData = reactive<RoleModel>({});
onMounted(() => {
    if (!isNil(props.role)) {
        Object.assign(formData, props.role);
    }
});

const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
});
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );

    if (formValid) {
        if (isNil(formData.id) || formData.id === 0) {
            // 新增
            const req = new Request<RoleModel>(
                '角色增加',
                omit(toRaw(formData), ['id']),
            );
            const r = await req.post();
            if (r.code > 100) {
                emit('yh-newrole', r.obj);
                return true;
            }
        } else {
            // 修改
            const req = new Request<RoleModel>('角色修改', toRaw(formData));
            const r = await req.post();
            if (r.code > 100) {
                emit('yh-updaterole', toRaw(formData));                
                return true;
            }
        }
    } else {
        return false;
    }
};
const submitForm = async () => {
    const r = await save();
    if (r) {
        emit('yh-closedialog');
    }
};

const submitAndNewForm = async () => {
    const r = await save();
    if (r) {
        formData.id = undefined;
        formData.name = undefined;
        formData.remark = undefined;
    }
};
</script>
